package com.tudouji.framework.task;

import com.tudouji.project.customer.service.ICustomerService;
import com.tudouji.project.mt.domain.MtShop;
import com.tudouji.project.mt.domain.MtWhin;
import com.tudouji.project.mt.domain.MtWhinitem;
import com.tudouji.project.mt.service.*;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.service.IOrganizationService;
import com.tudouji.project.organization.service.ISupplierService;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.service.ISalesspecificationService;
import com.tudouji.project.store.domain.Stockunit;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.service.IStockunitService;
import com.tudouji.project.store.service.IStorehouseroomService;
import com.tudouji.project.store.service.IStoreroomService;
import com.tudouji.framework.task.MeituanDataProcessUtil.ProcessWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;


/**
 * 美团数据加工
 */
@Service("mtwhindp")
@Slf4j
public class MeituanWhinDataProcessing {
    @Autowired
    private ISupplierService supplierService;

    @Autowired
    private MeituanDataProcessUtil meituanDataProcessUtil;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ISalesspecificationService salesspecificationService;

    @Autowired
    private IStoreroomService storeroomService;

    @Autowired
    private IStorehouseroomService storehouseroomService;

    @Autowired
    private IStockunitService stockunitService;

    @Autowired
    private IMtShopService mtShopService;

    @Autowired
    private IMtWhinService mtWhinService;
    @Autowired
    private IMtWhinitemService mtWhinitemService;

    @Autowired
    private IMtWhoutService mtWhoutService;
    @Autowired
    private IMtWhoutitemService mtWhoutitemService;




    /**
     * 处理美团入库单的数据加工
     */
    public void whinProcess(){
        log.info("============美团入库单数据加工开始 ========");
        List<MtShop> mtShopList = mtShopService.selectMtShopList(new MtShop());
        for(MtShop mtShop:mtShopList){
            if(mtShop.getStatus()==1){
                whinProcessForShop(mtShop);
            }
        }
        log.info("============美团入库单数据加工完成 ========");
    }

    /**
     * 处理某一店铺的入库单
     * @param mtShop
     */
    public void whinProcessForShop(MtShop mtShop){
        MtWhin lookup = new MtWhin();
        //设置查询条件，查询状态为 1 - 初始，或者状态为 10 - 资料不全的美团入库单主表数据
        //需要有时间范围，仅查询推送数据前 n 天 到当前的数据即可
        //Long startBiztime = DateUtils.addDays(mtShop.getWhinAsyndate(),-3).getTime();
        Long startBiztime = mtShop.getPushdate().getTime();
        lookup.setStartBiztime(startBiztime);
        lookup.setMtShopld(mtShop.getId());
        //lookup.setStatus(1);
        List<MtWhin> mtWhinList = mtWhinService.selectMtWhinList(lookup);
        for(MtWhin mtWhin:mtWhinList){
            if(mtWhin.getStatus()!=1 && mtWhin.getStatus()!=10){
                continue;
            }
            mtWhin.setRemark("");
            whinProcessForWhinOrder(mtWhin,mtShop);
            //更新主表数据
            mtWhinService.updateMtWhin(mtWhin);
        }
    }

    /**
     * 为美团入库单进行数据加工
     * @param mtWhin
     */
    private boolean whinProcessForWhinOrder(MtWhin mtWhin,MtShop mtShop) {
        //首先获取组织信息
        Organization organization = meituanDataProcessUtil.getOrgnization(mtShop);
        mtWhin.setOrgId(organization.getId());
        mtWhin.setOrgName(organization.getName());

        //获取供应商信息，美团入库单中的供应商信息需要确认下来
        if(mtWhin.getType().intValue()==2){
            //type==2是采购入库单
            //mtWhin.getOppositeorgType() 1.供应商 2.组织机构 3.外销客户
            String supplierCode = mtWhin.getOppositeorgCode();
            Supplier supplier=null;
            ProcessWrapper<Supplier> supplierWrapper = meituanDataProcessUtil.getSupplier(supplierCode);
            if(supplierWrapper.isSuccess()){
                supplier=supplierWrapper.getTarget();
            }else{
                //资料不全
                mtWhin.setStatus(10);
                mtWhin.setRemark(supplierWrapper.getMessage());
                return false;
            }
            mtWhin.setSupplierid(supplier.getId());
            mtWhin.setSuppliername(supplier.getName());
        }

        //入库单类型匹配
        mtWhin.setErpType(meituanDataProcessUtil.getWhinErpTypeByMtType(false, mtWhin.getType()));
        if(mtWhin.getErpType()==null){
            mtWhin.setStatus(10);
            mtWhin.setRemark("入库单类型匹配错误");
            return false;
        }

        //判断同组织、跨组织,如果是跨组织，需要找到对方机构对应的内部供应商
        //以及，对应ERP的入库单类型匹配
        if(!diffOrgProcess(mtWhin,mtShop)){
            return false;
        }

        ProcessWrapper<Department> dprocessWrapper = meituanDataProcessUtil.getDepartment(mtShop);
        if(!dprocessWrapper.isSuccess()){
            mtWhin.setStatus(10);
            mtWhin.setRemark(dprocessWrapper.getMessage());
            return false;
        }

        mtWhin.setDepartmentguid(dprocessWrapper.getTarget().getGuid());
        //开始处理明细表数据
        if(whinprocessForWhinItems(mtWhin,mtShop)){
            mtWhin.setStatus(50);
            return true;
        }else{
            //明细表处理的过程中，主表状态其实已经处理过了，最终兜底
            mtWhin.setStatus(10);
            return false;
        }

    }

    /**
     * 跨组织处理，找到对方机构对应的内部供应商
     * @param mtWhin          美团入库单主表数据
     * @param mtShop          美团店铺
     * @return
     */
    private boolean diffOrgProcess(MtWhin mtWhin, MtShop mtShop) {

        //调拨入库、配送入库，可能需要处理跨组织的内部结算，其他类型入库单不需要处理
        if(!MeituanDataProcessUtil.whinDiffOrgMap.keySet().contains(mtWhin.getType())){
            return true;
        }

        //TODO 判断同组织还是跨组织，暂时不知道怎么判断
        boolean sameOrg = true;
        //判断跨组织交易逻辑
        Organization organization=null;  //入库交易的对方组织
        if(mtWhin.getOppositeorgType().intValue()==2){
            //对方机构类型如果是内部机构
            ProcessWrapper<Organization> orgProcessWrapper = meituanDataProcessUtil.getOrgByMtcode(mtWhin.getOppositeorgCode());
            if(!orgProcessWrapper.isSuccess()){
                mtWhin.setStatus(10);
                mtWhin.setRemark(orgProcessWrapper.getMessage());
                return false;
            }
            organization = orgProcessWrapper.getTarget();
            sameOrg = organization.getId().equals(mtWhin.getOrgId());
        } else {
            //入库交易的对方组织不是内部组织
            mtWhin.setStatus(10);
            mtWhin.setRemark("配送/调拨入库单的对方组织不是内部机构！");
            return false;
        }

        if(sameOrg){
            //同组织的，直接返回，不需要处理了
            return true;
        }

        mtWhin.setErpType(meituanDataProcessUtil.getWhinErpTypeByMtType(true, mtWhin.getType()));
        if(mtWhin.getErpType()==null){
            mtWhin.setStatus(10);
            mtWhin.setRemark("入库单类型匹配错误");
            return false;
        }

        ProcessWrapper<Supplier> supplierProcessWrapper = meituanDataProcessUtil.findSupplierByOrg(organization);
        if(!supplierProcessWrapper.isSuccess()){
            mtWhin.setStatus(10);
            mtWhin.setRemark(supplierProcessWrapper.getMessage());
            return false;
        }
        Supplier supplier = supplierProcessWrapper.getTarget();
        mtWhin.setSupplierid(supplier.getId());
        mtWhin.setSuppliername(supplier.getName());
        return true;
    }

    /**
     * 加工美团入库单明细表数据
     * @param mtWhin
     * @param mtShop
     */
    private boolean whinprocessForWhinItems(MtWhin mtWhin, MtShop mtShop) {
        MtWhinitem lookup = new MtWhinitem();
        lookup.setMtWhinid(mtWhin.getId());
        boolean processFlag = true;
        List<MtWhinitem> mtWhinitems = mtWhinitemService.selectMtWhinitemList(lookup);

        //没有明细数据
        if(mtWhinitems.size()==0){
            mtWhin.setStatus(10);
            mtWhin.setRemark("没有找到明细数据");
            return false;
        }

        for(MtWhinitem mtWhinitem:mtWhinitems){
            mtWhinitem.setRemark("");
            if(!whinProcessForWhinItem(mtWhinitem,mtWhin,mtShop)){
                processFlag=false;
            }
            //更新当前数据
            mtWhinitemService.updateMtWhinitem(mtWhinitem);
        }
        return processFlag;
    }

    /**
     * 加工某一条美团入库单明细表数据
     * @param mtWhinitem
     * @return
     */
    private boolean whinProcessForWhinItem(MtWhinitem mtWhinitem,MtWhin mtWhin,MtShop mtShop) {

        //处理物料信息
        ProcessWrapper<Salesspecification> spProcessWrapper = meituanDataProcessUtil.processSalesSpec(mtWhinitem.getGoodsCode(),mtShop);
        if(!spProcessWrapper.isSuccess()){
            mtWhin.setRemark(spProcessWrapper.getMessage());
            mtWhin.setStatus(10);
            mtWhinitem.setRemark(spProcessWrapper.getMessage());
            return false;
        }
        Salesspecification salesspecification = spProcessWrapper.getTarget();
        mtWhinitem.setProductguid(salesspecification.getProductguid());
        mtWhinitem.setProductname(salesspecification.getProductname());
        mtWhinitem.setSpguid(salesspecification.getGuid());
        mtWhinitem.setSpname(salesspecification.getName());

        //处理库房及库间
        ProcessWrapper<Storehouseroom> wareHouseWrapper = meituanDataProcessUtil.processWareHouse(mtWhinitem.getMtWhCode(),mtShop,salesspecification);
        if(!wareHouseWrapper.isSuccess()){
            mtWhin.setRemark(wareHouseWrapper.getMessage());
            mtWhin.setStatus(10);
            return false;
        }
        Storehouseroom storehouseroom = wareHouseWrapper.getTarget();
        Storeroom storeroom =meituanDataProcessUtil.storeroomMap.get(mtWhinitem.getMtWhCode());
        mtWhinitem.setStoreroomguid(storeroom.getGuid());
        mtWhinitem.setStoreroomname(storeroom.getName());
        mtWhinitem.setStorehouseguid(storehouseroom.getGuid());
        mtWhinitem.setStorehousename(storehouseroom.getName());


        //库存单位
        ProcessWrapper<Stockunit> stockunitProcessWrapper =meituanDataProcessUtil.processStockUnit(salesspecification.getStockunitid());
        if(!stockunitProcessWrapper.isSuccess()){
            mtWhin.setRemark(stockunitProcessWrapper.getMessage());
            mtWhinitem.setRemark(stockunitProcessWrapper.getMessage());
            mtWhin.setStatus(10);
            return false;
        }
        Stockunit stockunit = stockunitProcessWrapper.getTarget();
        mtWhinitem.setStockunitid(stockunit.getId());
        mtWhinitem.setStockunitname(stockunit.getUnitName());
//        Stockunit mtStockunit = stockunitService.selectStockunitById(salesspecification.getMtStockunitId());
//        if(mtStockunit==null){
//            mtWhin.setRemark("物料的美团库存单位设置不正确");
//            mtWhinitem.setRemark("物料的美团库存单位设置不正确");
//            mtWhin.setStatus(10);
//            return false;
//        }
        //处理数量及单价
        BigDecimal rate = salesspecification.getMttostockUnitRate();
        if(rate==null || rate.compareTo(BigDecimal.ZERO)==0){
            mtWhin.setRemark("物料的美团单位转换率设置错误！");
            mtWhinitem.setRemark("物料的美团单位转换率设置错误！");
            mtWhin.setStatus(10);
        }
        mtWhinitem.setErpWeight(mtWhinitem.getAmount().multiply(rate));
        mtWhinitem.setErpPrice(mtWhinitem.getPrice().divide(rate));

        return true;
    }




}
